package com.renchunlin.looerpager.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.viewpager.widget.PagerAdapter
import com.renchunlin.looerpager.R

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/6/17.
 * PS: Not easy to write code, please indicate.
 */
class CarouselPagerAdapter(private val listPic: List<Int>) : PagerAdapter() {

    override fun getCount() = Int.MAX_VALUE

    //判断是否是否为同一张图片，这里返回方法中的两个参数做比较就可以
    override fun isViewFromObject(view: View, `object`: Any) = view == `object`

    //是用于往viewpage中添加控件，添加内容-设置viewpage内部东西的方法，如果viewpage内没有子空间滑动产生不了动画效果
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val item =
            LayoutInflater.from(container.context).inflate(R.layout.item_pager, container, false)
        val imageView = item.findViewById<ImageView>(R.id.cover)
        //设置数据
        //position=0 ==> 0%4=0
        //position=1 ==> 1%4=1
        //position=2 ==> 2%4=2
        //position=3 ==> 3%4=3
        //position=4 ==> 4%4=0
        //position=5 ==> 5%4=1
        //position=100 ==> 100%4=0
        val realPosition = position % listPic.size
        imageView.setImageResource(listPic[realPosition])

        val parent = imageView.parent as ViewGroup
        parent.removeAllViews()

        container.addView(imageView)
        return imageView
    }

    //销毁
    //是加入页面的时候，默认缓存三个，如不做处理，滑多了程序就会蹦-因为它默认是看三张图片，第四张图片的时候就会报错，还有就是不要返回父类的作用
    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as View?)
    }
}